package Exer9;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.function.Function;

public class GenericFileHandler {
    public static <T> void writeToFile(DataContainer<T> container, String filePath) throws IOException {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (T element : container.toList()) {
                writer.write(element.toString());
                writer.newLine();
            }
        }
    }

    public static <T> DataContainer<T> readFromFile(String filePath, Function<String, T> parser) throws IOException {
        DataContainer<T> resultContainer = new DataContainer<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = reader.readLine()) != null) {
                T element = parser.apply(line);
                resultContainer.add(element);
            }
        }
        return resultContainer;
    }
}
